package com.sr.service.impl;

import com.sr.enums.ResponseCode;
import com.sr.exception.BusinessException;
import com.sr.ibase.impl.BaseServiceImpl;
import com.sr.pojo.SysRolePermission;
import com.sr.service.IRolePernissionService;
import com.sr.util.ToolUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xiaochi
 * @date 2022/5/3 18:51
 * @desc RolePernissionServiceImpl
 */
@Service
public class RolePernissionServiceImpl extends BaseServiceImpl<SysRolePermission> implements IRolePernissionService {

    /**
     * 插入角色权限关联表数据
     * @param permissionsIds
     * @param roleId
     */
    @Override
    public void addRolePermission(List<String> permissionsIds,String roleId) {
        // 添加之前，先删除原来角色 id 对应的所有权限id
        SysRolePermission rolePermission = new SysRolePermission();
        rolePermission.setRoleId(roleId);
        this.deleteByWhere(rolePermission);
        // 权限id集合为空，表示删除该角色对应的所有权限
        if (permissionsIds.isEmpty()){
            return;
        }
        Date date = new Date();
        List<SysRolePermission> data = new ArrayList<>();
        for (String permissionId : permissionsIds){
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setId(ToolUtil.nextId());
            sysRolePermission.setPermissionId(permissionId);
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setCreateTime(date);
            data.add(sysRolePermission);
        }
        int result = this.insertBatch(data);
        if (result == 0){
            throw new BusinessException(ResponseCode.ERROR);
        }
    }
}
